<?php
/*
Plugin Name: qiushibaike
Plugin URI: http://www.hengha.info
Description: Crawl jokes from http://www.qiushibaike.com
Version: 4.0
Author: tomcat
Author URI: http://www.hengha.info
Text Domain: qiushibaike
Domain Path: /languages/
*/

function cron_add_small_interval($schedules)
{
    if (!isset($schedules['ten-minutes'])) {
        $schedules['ten-minutes'] = array(
            'interval' => 600,
            'display' => __('Ten Minutes', 'qiushibaike')
        );
    }
    if (!isset($schedules['three-minutes'])) {
        $schedules['three-minutes'] = array(
            'interval' => 180,
            'display' => __('Three Minutes', 'qiushibaike')
        );
    }

    return $schedules;
}

add_filter('cron_schedules', 'cron_add_small_interval');

/*
function load_plugin_textdomain() {
  load_plugin_textdomain( 'qiushibaike', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}

add_action( 'plugins_loaded', 'load_plugin_textdomain' );
 */

function prefix_activation()
{
    wp_schedule_event(time(), 'ten-minutes', 'joke_ten_minutes_event_hook');
    wp_schedule_event(time(), 'three-minutes', 'joke_three_minutes_event_hook');
}

register_activation_hook(__FILE__, 'prefix_activation');

function get_anonymous_user_id()
{
    $userId = username_exists('unkown');
    if ($userId == null) {
        $userId = wp_insert_user(array(
            'user_login' => 'unkown',
            'user_email' => 'unkown@hengha.info',
            'nickname' => '匿名',
            'display_name' => '匿名',
            'user_pass' => wp_generate_password(20),
            'role' => 'subscriber'
        ));
    }
    return $userId;
}

function get_user_id($user)
{
    if ($user) {
        $login = md5($user->login);
        $userId = username_exists($login);
        if ($userId == null) {
            $userId = wp_insert_user(array(
                'nickname' => $user->login,
                'display_name' => $user->login,
                'user_login' => $login,
                'user_email' => $login . '@hengha.info',
                'user_pass' => wp_generate_password(20),
                'role' => 'subscriber'
            ));
            $avatar = 'http://tuicool.qiniudn.com/th.jpg';
            if ($user->icon) {
                $avatar = sprintf('http://pic.qiushibaike.com/system/avtnew/%d/%d/medium/%s',
                    (int)($user->id / 10000), $user->id, $user->icon);
            }
            update_user_meta($userId, 'item_id', $user->id);
            update_user_meta($userId, 'avatar', $avatar);
        }
        return $userId;
    } else {
        return get_anonymous_user_id();
    }
}

function handle_jokes($model)
{
    $args = array(
        'post_type' => 'joke',
        'post_status' => 'publish',
        'posts_per_page' => 1
    );

    $categoryId = get_cat_ID('糗事百科');

    foreach ($model->items as $item) {
        $userId = get_user_id($item->user);
        $args['name'] = $item->id;
        $the_post = get_posts($args);
        if (!$the_post) {
            $imgUrl = '';
            if ($item->image) {
                $imgUrl = sprintf('<img src="http://pic.qiushibaike.com/system/pictures/%d/%d/medium/%s" />', (int)($item->id / 10000), $item->id, $item->image);
            }
            $tags = array('糗事百科');
            if ($item->image) {
                $tags[] = '有图';
            } else {
                $tags[] = '文本';
            }
            $content = '';
            if ($imgUrl && strlen($imgUrl) > 0) {
                $content = sprintf("<figure><figcaption>%s</figcaption>%s</figure>", strip_tags($item->content, '<br><br/><br />'), $imgUrl);
            } else {
                $content = '<p>' . strip_tags($item->content, '<br><br /><br>') . '</p>';
            }
            $postId = wp_insert_post(array(
                'post_title' => $item->id,
                'post_name' => $item->id,
                'post_content' => $content,
                'post_status' => 'publish',
                'post_author' => $userId,
                'post_type' => 'joke',
                //'post_format' => 'status',
                'post_category' => array($categoryId),
                'tags_input' => implode(',', $tags)
            ));

            update_post_meta($postId, 'published_at', $item->published_at);
            update_post_meta($postId, 'created_at', $item->created_at);
            update_post_meta($postId, 'item-id', $item->id);
        }
    }
}

function get_hot_jokes()
{
    $content = wp_remote_get('http://m2.qiushibaike.com/article/list/day?page=1&count=30',
        array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
            'httpversion' => '1.1',
            'timeout' => 120));
    $model = json_decode($content['body']);
    handle_jokes($model);
}

function get_suggest_jokes()
{
    $content = wp_remote_get('http://m2.qiushibaike.com/article/list/suggest?page=1&count=30',
        array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
            'httpversion' => '1.1',
            'timeout' => 120));
    $model = json_decode($content['body']);
    handle_jokes($model);
}

function get_joke_comments()
{
    global $wpdb;
    $gmnow = gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
    $id = $wpdb->get_var($wpdb->prepare("select max(a.ID) from $wpdb->posts a where a.post_date_gmt>=%s and not exists(select 1 from $wpdb->comments b where b.comment_post_ID=a.ID) and a.post_type='joke' and a.post_status='publish' ", $gmnow));
    if ($id) {
        $item_id = $wpdb->get_var($wpdb->prepare("select post_title from $wpdb->posts where ID=%d", $id));
        if ($item_id) {
            add_post_meta($id, 'last-check-comments', time(), true) or update_post_meta($id, 'last-check-comments', time(), true);
            $i = 2;
            $total = handle_comments($item_id, $id);
            while ($i <= $total) {
                handle_comments($item_id, $id, $i);
                $i++;
            }
        }
    }
}

function handle_comments($id, $post_id, $page = 1)
{
    $args = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);

    $content = wp_remote_get(sprintf('http://m2.qiushibaike.com/article/%d/comments?page=%d&count=50', $id, $page), $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request %d,%d,$d failed", $id, $post_id, $page));
        return;
    }
    $comments = json_decode($content['body']);
    $results = array();

    foreach ($comments->items as $comment) {
        $item = array(
            'comment_post_ID' => $post_id,
            'comment_approved' => 1,
            'comment_parent' => 0,
        );
        $item['comment_author_IP'] = $comment->id;
        $item['comment_content'] = $comment->content;
        $item['comment_date'] = current_time('mysql');

        $user_id = 0;

        $user_id = get_user_id($comment->user);

        $item['user_id'] = $user_id;
        $results[] = $item;
    }
    save_comments($results);
    return $comments->total;
}

function save_comments($comments)
{
    global $wpdb;
    foreach ($comments as $comment) {
        $temp = $wpdb->get_var($wpdb->prepare("select meta_id from $wpdb->commentmeta where meta_key='qiushibaike-comment-id' and meta_value=%s", $comment['comment_author_IP']));
        if (!$temp) {
            $id = wp_insert_comment($comment);
            add_comment_meta($id, 'qiushibaike-comment-id', $comment['comment_author_IP']);
        }
    }
}


function qiushibaike($atts)
{
    $atts = shortcode_atts(array(
        'action' => 'joke'
    ), $atts, 'stackoverflow');

    switch ($atts['action']) {
        case 'joke':
            get_suggest_jokes();
            break;
        case 'comment':
            get_joke_comments();
            break;
        default:
            break;
    }
}

add_shortcode('qiushibaike', 'qiushibaike');


add_action('joke_ten_minutes_event_hook', 'get_suggest_jokes');
add_action('joke_ten_minutes_event_hook', 'get_hot_jokes');
add_action('joke_three_minutes_event_hook', 'get_joke_comments');
function prefix_deactivation()
{
    wp_clear_scheduled_hook('joke_ten_minutes_event_hook');
    wp_clear_scheduled_hook('joke_three_minutes_event_hook');
}

register_deactivation_hook(__FILE__, 'prefix_deactivation');
?>
